/*
 * @(#)BobpleXmlView.java $version 2011. 5. 19.
 *
 */

package org.doit.android.bobple.server.common;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.AbstractView;

/**
 *
 * @author Choi HongKi
 */
@Component
public class BobpleXmlView extends AbstractView {

	@SuppressWarnings("unchecked")
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Assert.state(model.containsKey("success") && model.containsKey("value"), "Bobple XML must have two keys! : success & value");

		Object value = model.get("value");

		Assert.state(value instanceof List<?> || value instanceof Map<?, ?>, "instane of value must be List or Map");

		StringBuffer sbXML = new StringBuffer();

		sbXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
		sbXML.append("<bobple-response>\r\n");

		sbXML.append(String.format("<success>%s</success>\r\n", model.get("success")));

		if (value instanceof List) {
			for (Map<String, Object> oneValue : (List<Map<String, Object>>)value) {
				sbXML.append(String.format("<value>%s</value>\r\n", MapValueToXML(oneValue)));
			}
		} else {
			sbXML.append(String.format("<value>%s</value>\r\n", MapValueToXML((Map<String, Object>)value)));
		}

		sbXML.append("</bobple-response>");

		response.setContentType("application/xml;charset=UTF-8");
		response.getWriter().print(sbXML.toString());
	}

	private String MapValueToXML(Map<String, Object> mapValue) {
		StringBuilder sbToXML = new StringBuilder();

		for (Map.Entry<String, Object> entry : mapValue.entrySet()) {
			sbToXML.append(String.format("<%s>%s</%s>", entry.getKey(), entry.getValue(), entry.getKey()));
		}

		return sbToXML.toString();
	}
}